﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace RevitAddinSet
{
    public partial class AddinForm : Form
    {
        private static string _ExEDir = null; //exe所在路径
        private static string RevitPath = @"C:\ProgramData\Autodesk\Revit";
        private static List<string> RevitVer_List = new List<string>();

        public AddinForm()
        {
            InitializeComponent();

            //检查版本信息
            CheckRevit();

            //初始化DataGridView
            InitDataGridView();
        }

        #region 窗体方法

        /// <summary>
        /// 取消行选中状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
        {
            dataGridView.ClearSelection();
        }

        /// <summary>
        /// 初始化-分发addin
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSetUp_Click(object sender, EventArgs e)
        {
            //获得用户选择的版本
            List<string> selectVer_List = GetSelectVerList();

            if (selectVer_List.Count != 0)
            {
                //获得exe路径
                GetEXEPath(); 

                //获得addin和dll文件路径
                string addinPath = _ExEDir + @"\FsAddinApp.addin";
                string dllPath = _ExEDir + @"\FsAddInManager.dll";

                //根据dll的实际路径替换addin文件中的路径信息
                ChangeAddinPath(addinPath,dllPath);
                 
                //将addin文件复制到Revit各版本下
                if (!File.Exists(addinPath))
                {
                    labelTips.Text = "释放addin文件失败！请检查FsAddinApp.addin是否与exe程序同一目录.";
                    labelTips.ForeColor = Color.Red;
                    return;
                }

                foreach (var item in selectVer_List)
                {
                    File.Copy(addinPath, item + @"\FsAddinApp.addin", true);
                }

                labelTips.Text = "释放addin文件成功！";
                labelTips.ForeColor = Color.ForestGreen;
            }
            else
            {
                labelTips.Text = "未找到Revit 安装路径.请确保Revit 已经安装.";
                labelTips.ForeColor = Color.Red;
            }
        }

        /// <summary>
        /// 卸载addin
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonUnload_Click(object sender, EventArgs e)
        {
            try
            {
                //获得用户选择的版本
                List<string> selectVer_List = GetSelectVerList();

                if (selectVer_List.Count != 0)
                {
                    foreach (var item in selectVer_List)
                    {
                        if (File.Exists(item + @"\FsAddinApp.addin"))
                        {
                            File.Delete(item + @"\FsAddinApp.addin");
                        }
                    }
                    labelTips.Text = "删除addin文件成功！";
                    labelTips.ForeColor = Color.ForestGreen;
                }
                else
                {
                    labelTips.Text = "未找到Revit 安装路径.请确保Revit 已经安装.";
                    labelTips.ForeColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                labelTips.Text = "删除addin文件失败！请使用管理员权限启动,或尝试手动删除addin文件.";
                labelTips.ForeColor = Color.Red;
            }
        }

        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        #endregion

        #region 内部方法

        /// <summary>
        /// 检查Revit 版本信息
        /// </summary>
        private void CheckRevit()
        {
            if (!Directory.Exists(RevitPath))
            {
                labelTips.Text = "未找到Revit 安装路径.请确保Revit 已经安装.";
                labelTips.ForeColor = Color.Red;
                return;
            }

            DirectoryInfo TheFolder = new DirectoryInfo(RevitPath + @"\Addins");
            foreach (DirectoryInfo NextFolder in TheFolder.GetDirectories())
            {
                RevitVer_List.Add(NextFolder.FullName) ;
            }
        }

        /// <summary>
        ///当前"应用"dll所在目录,结尾不包括"\\"
        /// </summary>
        /// <returns></returns>
        private void GetEXEPath()
        {
            if (!String.IsNullOrEmpty(_ExEDir))
            {
                return;
            }

            string location = Assembly.GetExecutingAssembly().Location; 
            _ExEDir = System.IO.Path.GetDirectoryName(location); 
        }

        /// <summary>
        /// 替换addin中的路径
        /// </summary>
        /// <param name="addinPath"></param>
        /// <param name="dllPath"></param>
        private static void ChangeAddinPath(string addinPath, string dllPath)
        {
            if (!File.Exists(addinPath))
            {
                return;
            }
           
            XElement xelement = XElement.Load(addinPath);
            foreach (XNode node in xelement.Nodes())
            {
                if (node.NodeType == XmlNodeType.Element)
                {
                    XElement sub = node as XElement;

                    if (sub != null)
                    {
                        foreach (XNode item in sub.Nodes())
                        {
                            XElement sub2 = item as XElement;
                            if (sub2.Name == "Assembly")
                            {
                                sub2.Value = dllPath;
                            }
                        }
                    }
                }
            }

            xelement.Save(addinPath);
        }

        /// <summary>
        /// 初始化dataGridView
        /// </summary>
        private void InitDataGridView()
        { 
            if(RevitVer_List.Count > 0)
            { 
                foreach(var version in RevitVer_List)
                { 
                    int rowIndex = dataGridView.Rows.Add();
                    dataGridView.Rows[rowIndex].Cells[0].Value = version.Substring(version.Length-4);
                }
            }
        }

        /// <summary>
        /// 获得用户选择的版本
        /// </summary>
        private List<string> GetSelectVerList()
        { 
            List<string> selectVer_List = new List<string>();

            //获得勾选行的版本号
            for (int i = 0; i < dataGridView.Rows.Count; i++)
            {
                if (Convert.ToBoolean(dataGridView.Rows[i].Cells["CheckBox"].EditedFormattedValue))
                {
                    string version = dataGridView.Rows[i].Cells["Version"].Value.ToString();
                    foreach(var v in RevitVer_List)
                    { 
                        if(v.Contains(version))
                        { 
                            selectVer_List.Add(v);
                        }
                    }
                }
            }

            return selectVer_List;
        }

        #endregion
    }
}
